/**
 * 操作日志拦截器
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Reflector } from '@nestjs/core';
import { LogService } from '../../modules/log/log.service';
import { LogType, LogLevel } from '../../interfaces/log.interface';
import { OPERATION_LOG_KEY, OperationLogOptions } from '../decorators/operation-log.decorator';

@Injectable()
export class OperationLogInterceptor implements NestInterceptor {
  constructor(
    private readonly reflector: Reflector,
    private readonly logService: LogService,
  ) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const startTime = Date.now();
    const request = context.switchToHttp().getRequest();
    const logOptions = this.reflector.get<OperationLogOptions>(
      OPERATION_LOG_KEY,
      context.getHandler(),
    );

    if (!logOptions) {
      return next.handle();
    }

    return next.handle().pipe(
      tap({
        next: (data) => {
          // 记录成功的操作日志
          this.logService.create(
            LogType.OPERATION,
            LogLevel.INFO,
            request,
            Date.now() - startTime,
            JSON.stringify(data),
          ).catch(err => {
            console.error('Failed to save operation log:', err);
          });
        },
        error: (error) => {
          // 记录失败的操作日志
          this.logService.create(
            LogType.OPERATION,
            LogLevel.ERROR,
            request,
            Date.now() - startTime,
            undefined,
            error.message,
          ).catch(err => {
            console.error('Failed to save operation log:', err);
          });
        },
      }),
    );
  }
} 